/**
 * @description: 钉钉授权登录及用户信息获取 service
 * @version: 0.0.1
 * @author: z..
 * @Date: 2023-06-12 18:16:39
 */

import { Provide, Inject, httpError } from '@midwayjs/core';
import { Context } from '@midwayjs/koa';
import { RobotWebapiRecordsModel } from "../entity/robot_webapi_records.method";
import { RobotWebapiLogsModel } from "../entity/robot_webapi_logs.method";
import { ScheduleTasksWebapiService } from "./schedule.tasks.webapi.service"

@Provide()
export class DingtalkRobotWebapiService {
  @Inject()
  ctx: Context;

  @Inject()
  RobotWebapiRecordsModel: RobotWebapiRecordsModel;

  @Inject()
  RobotWebapiLogsModel: RobotWebapiLogsModel;

  @Inject()
  ScheduleTasksWebapiService: ScheduleTasksWebapiService;

  /**
   * webapi分页查询
   * @param {*} pageSize 
   * @param {*} pageNum 
   * @param {*} searchKey 
   */
  async getWebapiPage(params: any): Promise<any> {
    const { ctx } = this;
    const total = await this.RobotWebapiRecordsModel.getTotalNum(params);
    let res = {
      total: total[0].num,
      lists: [],
      id: ctx.unionId
    }

    if (total[0].num) {
      const resList = await this.RobotWebapiRecordsModel.getDataByPage(params);
      res.lists = resList;
    }
    return res;
  }

  /**
   * 新增webapi信息
   * @param {*} webapiName 
   * @param {*} webapiContent 
   * @param {*} webapiType
   * @param {*} webapiEndtime 
   * @param {*} webapiStatus 
   * @param {*} webapiUserid 
   * @param {*} webapiUsername 
   * @param {*} webapiConfig
   * @param {*} brandId
   * @param {*} brandName
   * @param {*} projectId
   * @param {*} projectName
   * @param {*} testingInterval
   * @param {*} sendSuccessMsg
   * @param {*} webapiMethod
   * @param {*} webapiDomain
   * @param {*} webapiPath
   * @param {*} webapiData
   * @param {*} webapiCheck
   * @param {*} createdUserid
   * @param {*} createdUsername
   */
  async createWebapi(params: any): Promise<any> {
    const { ctx } = this;
    const userInfo = ctx.userInfo;

    //  负责人名称和id
    let _userid = [];
    let _username = [];
    params.webapiUserid.forEach(item => {
      _userid.push(item.userid);
      _username.push(item.name);
    });

    // 新增
    return await this.RobotWebapiRecordsModel.insertWebapi({
      webapiName: params.webapiName,
      webapiContent: params.webapiContent || "",
      webapiType: params.webapiType,
      webapiEndtime: params.webapiEndtime,
      webapiStatus: "NOT_START",
      webapiUserid: _userid.join(","),
      webapiUsername: _username.join(","),
      webapiConfig: JSON.stringify(params.webapiConfig),
      brandId: params.brandId || null,
      brandName: params.brandName || "",
      projectId: params.projectId || null,
      projectName: params.projectName || "",
      testingInterval: params.testingInterval,
      sendSuccessMsg: params.sendSuccessMsg,
      webapiMethod: params.webapiMethod,
      webapiDomain: params.webapiDomain,
      webapiPath: params.webapiPath || "",
      webapiCheck: params.webapiCheck || "",
      webapiData: JSON.stringify(params.webapiData),
      webapiClass: params.webapiClass,
      createdUserid: userInfo.id,
      createdUsername: userInfo.nick,
    });
  }

  /**
   * 更新webapi信息
   * @param {*} id 
   * @param {*} webapiName 
   * @param {*} webapiContent 
   * @param {*} webapiType
   * @param {*} webapiEndtime 
   * @param {*} webapiStatus 
   * @param {*} webapiUserid 
   * @param {*} webapiUsername 
   * @param {*} webapiConfig
   * @param {*} brandId
   * @param {*} brandName
   * @param {*} projectId
   * @param {*} projectName
   * @param {*} testingInterval
   * @param {*} sendSuccessMsg
   * @param {*} webapiMethod
   * @param {*} webapiDomain
   * @param {*} webapiPath
   * @param {*} webapiData
   * @param {*} webapiCheck
   * @param {*} createdUserid
   * @param {*} createdUsername
   * @returns 
   */
  async updateWebapi(params: any): Promise<any> {
    //  查询当前任务状态
    const task = await this.RobotWebapiRecordsModel.getWebapiById(params.id);
    if (!task || !task.length) {
      throw new httpError.BadRequestError("任务信息不存在，更新失败！");
    }
    if (task[0].webapi_status === "START") {
      throw new httpError.BadRequestError("任务信息进行中，更新失败");
    }
    //  负责人名称和id
    let _userid = [];
    let _username = [];
    params.webapiUserid.forEach(item => {
      _userid.push(item.userid);
      _username.push(item.name);
    });

    // 更新任务通知
    return await this.RobotWebapiRecordsModel.updateWebapiById({
      id: params.id,
      webapiName: params.webapiName,
      webapiContent: params.webapiContent || "",
      webapiType: params.webapiType,
      webapiEndtime: params.webapiEndtime,
      webapiStatus: "NOT_START",
      webapiUserid: _userid.join(","),
      webapiUsername: _username.join(","),
      webapiConfig: JSON.stringify(params.webapiConfig),
      brandId: params.brandId || null,
      brandName: params.brandName || "",
      projectId: params.projectId || null,
      projectName: params.projectName || "",
      testingInterval: params.testingInterval,
      sendSuccessMsg: params.sendSuccessMsg,
      webapiMethod: params.webapiMethod,
      webapiDomain: params.webapiDomain,
      webapiPath: params.webapiPath || "",
      webapiCheck: params.webapiCheck || "",
      webapiClass: params.webapiClass,
      webapiData: JSON.stringify(params.webapiData),
    });
  }


  /**
  * 删除webapi信息
  * @param {*} id
  * @returns 
  */
  async delWebapiById(params: any): Promise<any> {
    //  查询当前任务状态
    const task = await this.RobotWebapiRecordsModel.getWebapiById(params.id);
    if (task && task[0] && task[0].webapi_status != "START") {
      // 删除webapi信息和对应的日志
      return await this.RobotWebapiRecordsModel.delWebapiById(params.id);
    } else {
      throw new httpError.BadRequestError("任务状态为进行中或通知不存在，删除失败！");
    }
  }

  /**
   * 手动测试api
   * @param {*} id 
   */
  async testingWebapiByid(id: number): Promise<any> {
    //  查询当前任务状态
    const task = await this.RobotWebapiRecordsModel.getWebapiById(id);
    if (!task || !task.length) throw new httpError.BadRequestError("当前任务不存在");
    //  调用测试接口
    return await this.ScheduleTasksWebapiService.webApiManualTesting(task[0]);
  }

  /**
   * 修改webapi的状态
   * @param {*} params 
   * @returns 
   */
  async updateWebapiStatus(params: any): Promise<any> {
    //  查询当前任务状态
    const task = await this.RobotWebapiRecordsModel.getWebapiById(params.id);
    if (!task || !task.length) throw new httpError.BadRequestError("当前任务不存在");
    //  修改webapi的状态
    return await this.RobotWebapiRecordsModel.updateWebapiStatus(params);
  }

  /**
   * 查询当前id的测试日志数量
   * @param {*} id 
   * @returns 
   */
  async getWebapiTestingLogsById(id: number): Promise<any> {
    //  查询
    const task = await this.RobotWebapiLogsModel.getWebapiTestingLogsById(id);
    return task[0].num;
  }

  /**
   * 查询当前id的测试日志数量
   * @param {*} id 
   * @returns 
   */
  async webApiLogs(id: number): Promise<any> {
    return await this.RobotWebapiLogsModel.webApiLogs(id);
  }
}